package org.bopis.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.bopis.domain.Bopi;
import org.bopis.form.BuscarForm;
import org.bopis.services.impl.BopisServicioImpl;
import org.bopis.services.interfaz.BopisServicio;
import org.bopis.utilidades.Utilidades;


public class BuscarBopisAction extends CustomBaseAction {
	
	private static Logger log = Logger.getLogger(BuscarBopisAction.class);
	
    public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    	
    	log.info("Incicio");
    	
    	String ok = "false";
    	
	    	   	
    	BuscarForm f = (BuscarForm) form;
    	
    	
    	if (!Utilidades.isVacia(req.getParameter("fecha"))) {
    		req.setAttribute("fecha", req.getParameter("fecha"));
    	}
    	else {
    		req.setAttribute("fecha", f.getFecha());
    	}
    	
    	if (!Utilidades.isVacia(req.getParameter("tomo"))) {
    		req.setAttribute("tomo", req.getParameter("tomo"));
    	}
    	else {
    		req.setAttribute("tomo", f.getTomo());
    	}
    	
    	if (!Utilidades.isVacia(req.getParameter("ok"))) {
    		ok = req.getParameter("ok");
    	}
    	
    	
    	log.info("fecha: " + f.getFecha());
    	log.info("tomo: " + f.getTomo());
    	log.info("ok: " + ok);
    	
    	
		//Buscamos los bopis por fecha
		List<Bopi> listaBopis = null;
		
		BopisServicio bopisServicio = new BopisServicioImpl();
		
		if ("ok".equalsIgnoreCase(ok)) {
			//Llamamos al servicio
			listaBopis = bopisServicio.buscarPorFechaYTomo(f.getFecha(), f.getTomo());
		}
			
		if (!Utilidades.isVacia(listaBopis)) {
			log.info("listaBopis.get(0).getNombre(): " + listaBopis.get(0).getNombre());
			req.setAttribute("bopi", listaBopis.get(0));
		}
		else {
			req.setAttribute("bopi", null);
		}	
    	
    	
    	return map.findForward("Success");
    }
}
